/*
 * FuncionServlets.java
 *
 * Created on 30 de marzo de 2007, 17:02
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package util;

import javax.servlet.*;
import javax.servlet.http.*;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.io.*;
import java.net.*;
import java.util.Iterator;
import java.util.List;


import javax.servlet.http.*;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
 *
 * @author Administrador
 */
public class FuncionServlets {
    
    /**
     * Obtiene los parametros importantes
     * @param request
     * @param response
     */
    public static void obtenerParametros(HttpServletRequest request,
            HttpServletResponse response, Boolean volver) {
        Map params = request.getParameterMap();
        Set keyslist = params.keySet();
        
        // Obtenemos los parametros
        Iterator keys = keyslist.iterator();
        String key;
        String value[];
        StringBuilder parametros = new StringBuilder();
        while (keys.hasNext()) {
            key = (String)keys.next();
            if (key.charAt(0) != '_'){
                value = request.getParameterValues(key);
                if (value.length == 1){
                    parametros.append(key + "=" + value[0] + "&");
                }else{
                    int i=0;
                    while (i<value.length){
                        
                        if (i == 0){
                            parametros.append(key + "=" +value[i] );
                        }else{
                            parametros.append(":" + value[i] );
                        }
                        
                        i++;
                    }
                    parametros.append("&");
                }
            }
        }
        
        // Guardo en sesion los atributos
        HttpSession session = request.getSession(true);
        String atributosUrlAnterior = "";
        
        if (session.getAttribute("atributosUrl") == null){
            session.setAttribute("atributosUrl", "");
            session.setAttribute("abributosUrlAnterior", "");
        }
        
        atributosUrlAnterior = (String) session.getAttribute("atributosUrl");
        
        session.setAttribute("loginUrl", parametros.toString());
        if (volver && !atributosUrlAnterior.equals(parametros.toString())){
            session.setAttribute("atributosUrlAnterior", atributosUrlAnterior);
            session.setAttribute("atributosUrl", parametros.toString());
        }
    }
    /**
     * Graba los archivos enviados por resquest, los graba en el
     * directorio q se especifica en el recurso negocio.properties dependiendo
     * del tipo pasado por parametro (foto=1/documento=2)
     * @param request
     */
    public static void grabarArchivosDesdeRequest(HttpServletRequest request, int tipo)
    throws FileUploadException, Exception{
        
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        Recurso r = new Recurso("negocio.properties");
        PrintWriter out=null;
        
        // Parse the request
        /* FileItem */
        List  items = upload.parseRequest(request);
        
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            
            if (!item.isFormField()) {
                String fieldName = item.getFieldName();
                String fileName = item.getName();
                String contentType = item.getContentType();
                boolean isInMemory = item.isInMemory();
                long sizeInBytes = item.getSize();
                if(sizeInBytes!=0){
                    File uploadedFile = null;
                    if (fieldName.equals("fileFoto")){
                        uploadedFile = new File(r.obtenerPropiedad("dirGuardaFotos"),fileName);
                    } else if (fieldName.equals("fileDocumento")){
                        uploadedFile = new File(r.obtenerPropiedad("dirGuardaDocumentos"),fileName);
                    }
                    item.write(uploadedFile);
                }
            }
        }
    }
    
}
